#!/usr/bin/env python
# coding=utf-8
#-------------------------------------------------------------------------------
# Name:        模块1
# Purpose:
#
# Author:      vavava
#
# Created:     05/11/2012
# Copyright:   (c) vavava 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

import re,threading
from vavava import httpclient

class GoogleFinder(object):
    """find google server ip(s) on internet"""
    def __init__(self):
        self.site='www.google.com'
        self.mutex = threading.Lock()
        self.ip_url_list=[]
        self.ips=[]
        self.ips_available=[]
        self.ip_order_list=[]

    def find(self,site,timeout=33):
        if site is not None:
            self.site=site
            print("get links")
            if self.get_ips_url(site,timeout) is None:
                print("get links failed")
                return
            print("get ips")
            if self.get_ips(timeout):
                print("get ips failed")
                return
            print("order")
            if self.ping_order():
                print("order failed")
                return
            print("order ok")

    def check(self,filename='./ips'):
        if self.load_ips(filename):
            self.ping_order()
        else:
            print("no ip saved,run find to get ip list")

    def get_ips_url(self,site=('www.google.com'),timeout=33):
        self.client = httpclient.HttpClient(req_timeout=timeout)
        quary_url=r'http://just-ping.com/index.php?vh='+site+'&c=&s=ping%21'
        print("get:",quary_url)
        get_data=self.client.Get(quary_url)
        htmltext=get_data.decode('utf-8')
        print(htmltext)

        reg_str="xmlreqGET\\(\'(?P<url>[^\']*)\',"
        reg=re.compile(reg_str,re.X)
        match=reg.findall(htmltext)
        if match:
            for each in match:
                each=r'http://just-ping.com/'+each
                self.ip_url_list.append(each)
            for each in match:
                print(each)
            return match
        else:
            print('not match:',htmltext)

    def get_ips(self,timeout=33):
        """ get ip from each url """
        for url in self.ip_url_list:
            client= httpclient.HttpClient(req_timeout=timeout)
            #client.header_refer_=r'http://just-ping.com/api/pingproxy.php?host=www.google.com'
            htmltext=client.Get(url)
            if htmltext:
                htmltext=htmltext.decode('utf-8')
                print(htmltext)
                self.ips.append(htmltext)
            else:
                print('failed on get:'+url)

        for ip in self.ips:
            reg_str=r'(?P<ip>\d*\.\d*\.\d*\.\d*)'
            reg=re.compile(reg_str,re.X)
            match=reg.findall(ip)
            if match:
                self.ips_available.append(match[0])
                print("match:",match[0])
            else:
                print('not match:',ip)

    def save_ips(self):
        import os
        if len(self.ip_order_list) <= 0 or len(self.ips_available) <= 0:
            return
        f=open(self.site,"w")
        if len(self.ip_order_list) > 0:
            #f.writelines('#'+self.fetch_url)
            for line in self.ip_order_list:
                f.writelines(r'%f,%s'%line)
                f.writelines(os.linesep)
        else:
            if len(self.ips_available) > 0:
                #f.writelines('#'+self.fetch_url)
                f.writelines('-1,'+self.ips_available)
                f.writelines(os.linesep)
        f.close()

    def load_ips(self,filename=""):
        if not os.path.isfile(filename):
            return
        f=open(filename,"r")
        if f.readable():
            iplist = f.readlines()
            self.ips_available = []
            for ip in iplist:
                if ip.find('#') < 0:
                    ip=ip.replace('\r','')
                    ip=ip.replace('\n','')
                    tmp=ip.split(',')
                    if len(tmp) > 1:
                        self.ips_available.append(tmp[1])
                else:
                    self.fetch_url = ip.replace('#','')
        f.close()
        if len(self.ips_available)>0:
            return True

    def ping_order(self,count=5):
        from vavava.ping1 import do_one
        import socket
        for ip in self.ips_available:
            print(r'ping ', ip)
            try:
                destIP = socket.gethostbyname(ip)
            except socket.gaierror as e:
                print("\nPYTHON-PING: Unknown host: %s (%s)" % (ip, e.args[1]))
                continue

            total=0
            total_count=count
            for c in range(count):
                delay=do_one(destIP, timeout=1000, mySeqNumber=c, numDataBytes=55)
                if delay != None:
                    total += delay
                else:
                    total_count -= 1
                    print("timeout:",ip)
            self.ip_order_list.append((total/total_count,ip))
            print ('delay:',ip,',',total/total_count)
        self.ip_order_list.sort()
        self.save_ips()
        print(self.ip_order_list)

    def save2hostFile(self,site):
        import platform,os,sys
        import vavava.util
        self.load_ips(site)
        hostFile=""
        sysvar=platform.system()
        if sysvar.find("Windows") != -1:
            root = os.environ.get("SYSTEMROOT")
            hostFile = root+r'\System32\drivers\etc\hosts'
        else:
            if sysvar.find("Linux") != -1:
                hostFile=r'/etc/hosts'
            else: #osx
                hostFile=r'/private/etc/hosts'
        f=open(file=hostFile,mode="r+")
        if not f.readable():
            return False
        else:
            lines=f.readlines()
            f.close()

        f1=open(file=hostFile+".bak",mode="w")

        for i in range(0,len(lines)):
            lineTrim=lines[i].replace('\n','')
            if re.findall("(^\s*#)",lineTrim,re.MULTILINE):
                continue
            if re.findall("(^\s*$)",lineTrim,re.MULTILINE|re.A):
                continue
            reg_str=r'(\s+%s\s*$)'%site
            reg_str=reg_str.replace('.',r'\.')
            if re.findall(reg_str,lineTrim,re.MULTILINE|re.I|re.A):
                lines[i] = '%s  %s\n'%(self.ips_available[0],site)
                break
        else:
            lines.insert(0,'%s  %s\n'%(self.ips_available[0],site))
        f1.writelines(lines)
        f1.close()
        f=open(file=hostFile,mode="w")
        f.writelines(lines)
        f.close()
        return True




def find(site='www.google.com'):
    gf=GoogleFinder()
    gf.find(site)

def check(site='www.google.com'):
    gf=GoogleFinder()
    gf.check(site)

def usage():
    print(
        """googleFinder [-check 0|1|2][-sites site[|site[|..]]][-save site[|site[|..]]]
                -check = 0:query
                         1:check
                         2:save 2 host file
        """
    )

def main():
    from vavava import util
    import sys
    argv_dic=util.parse_argvs(sys.argv)
    sites='www.google.com'
    save_list=[]
    chk_level=0 # 0:check  1:query 2:save 2 host file
    if argv_dic:
        if argv_dic.get('-sites'):  sites=argv_dic.get('-sites').split('|')
        if argv_dic.get('-check'):  chk_level=int(argv_dic.get('-check'))
        if argv_dic.get('-save'):   save_list=argv_dic.get('-save').split('|')
    else:
        usage()
        return

    if chk_level < 2:
        for site in sites:
            if chk_level == 0:
                find(site)
            if chk_level == 1:
                check(site)
    if len(save_list) > 0:
        for site in save_list:
            gf=GoogleFinder()
        gf.save2hostFile(site)


if __name__ == '__main__':
    main()
